// index page
// ============

define([ 'require', 'zepto', 'wx', 'ejs', 'bscroll','datePicker', 'sui' ],
    function(require, $, wx, ejs, BScroll) {
      return {
        init : function(data) {
          this.suppliers = data.suppliers;
          this.sets = data.sets
          this.countrySuppliers = ['Alamo', 'Enterprise', 'National']
          this.setCategories = data.setCategories
          this.initPage();
          this.initlocalStorage();
          this.initBrandPicker();
          this.initPicker();
          this.initSelectCity();
          this.initDatetimePicker();
          this.initSets();
          this.bindSubmit(data.isLogin);
          this.initHotCity();
          this.bindCitySearch();
        },
        
        initPage: function() {
          //点击索引查询城市
//          $('body').on('click', '.letter a, .city-letter a', function () {
//            var s = $(this).html();
//            var name = $(this).data("name")
//            $(".contacts-" + name).scrollTop($('#' + name + '-' + s).offset().top);
//          });
          var that = this;
          var countrycode = $("input[name='countryCode']").val();
          var countrycodes = countrycode.split(",");
          $(".city-name").addClass("hide");
          for(var i in countrycodes) {
            $(".city-name").each(function(e){
              if($(this).data("country") == countrycodes[i]) {
                $(this).removeClass("hide")
              }
            })
          }
          
          // that.initClickable();
          // 进入页面时刷新
          if ((/iphone|ipod|ipad.*os 5/gi).test(navigator.appVersion)) {
              window.onpageshow = function(event) {
                  if (event.persisted) {
                      window.location.reload() 
                  }
              };
          }else{
              onload=function(){
                  var refreshedId=document.getElementById("refreshed");
                  if(refreshedId.value=="no"){
                      refreshedId.value="yes";
                     } else{
                       refreshedId.value="no";
                       location.reload();
                   }
              }
          }
          
        },
        
        initClickable: function() {
          var that = this,
              countryEle = $("[name='countryName']")
              brandEle = $("#brand"),
              methodEle = $("#method"),
              packageTypeEle = $("#package-type")
          
          if(!countryEle.val()) {
            brandEle.prop("disabled", true);
          }
          
          if(!brandEle.val()) {
            methodEle.prop("disabled", true);
            packageTypeEle.prop("disabled", true);
            
          } 
          if(!methodEle.val()) {
            packageTypeEle.prop("disabled", true);
          }
          
          if(!packageTypeEle.val()) {
            packageTypeEle.prop("disabled", true);
          }
        },       
        
        initlocalStorage: function() {
          var that = this;
          
          if(window.localStorage.length > 0 ) {
            var storage= JSON.parse(window.localStorage.localData);
            for(var i=0;i<storage.length;i++){
              //console.log(storage[i].name)
              
              if(storage[i].name == 'supplierName') {
                $("#brand").val(storage[i].value);
              } else if(storage[i].name == 'pickupLocationName'){
                $(".pick-up-val").val(storage[i].value)
              }  else if(storage[i].name == 'returnLocationName'){
                $(".drop-off-val").val(storage[i].value)
              } else if(storage[i].name == 'pickupLocationCountry') {
                $(".pick-up-id").data('country',storage[i].value)
              } else if(storage[i].name == 'pickupDate') {
                var date = storage[i].value.split(" ")[0].split("-")
                var time =storage[i].value.split(" ")[1]
                $(".pick-up-layout .name").html(date[0]+"年"+date[1]+'月'+date[2]+'日');
                $(".pick-up-layout .time-box").html(time)
                $("input[name='"+ storage[i].name +"']").val(storage[i].value)
              } else if(storage[i].name == 'returnDate') {
                var date = storage[i].value.split(" ")[0].split("-")
                var time =storage[i].value.split(" ")[1]
                $(".drop-off-layout .name").html(date[0]+"年"+date[1]+'月'+date[2]+'日');
                $(".drop-off-layout .time-box").html(time)
                $("input[name='"+ storage[i].name +"']").val(storage[i].value)
              } else if(storage[i].name == 'typeName') {
                $("#method").val(storage[i].value)
              } else if(storage[i].name == 'setCategoryName') {
                $("#package-type").val(storage[i].value)
              }
              $("input[name='"+ storage[i].name +"']").val(storage[i].value)
            }
          }
          
          that.initClickable();
          
        },
        
        initBrandPicker: function() {
          var that = this;
          $(document).on("click", ".brand-item", function() {
            if(!$(".selected-val").val()) {
              $.toast("请先选择国家");
              return
            } else {
              $("#brand").prop("disabled", false);
            }
          })
          
          $(document).on("change", "#brand", function() {
            if($(this).val()) {
              $("#method").prop("disabled", false).val("");
              $("#package-type").prop("disabled", false).val("");
            } else {
              $("#package-type").prop("disabled", true).val("");
              $("#method").prop("disabled", true).val("");
            }
          })
          
          $(document).on("change", ".pick-up-id", function() {
            console.log("改变")
          })
          
          $(document).on("change", "#method", function() {
            if(!$(this).val()) {
              $("#package-type").prop("disabled", true).val("");
            } else {
              $("#package-type").prop("disabled", false).val("");
            }
          })
          
            
          
          $(document).on("click", ".method-item", function() {
            if(!$(".selected-val").val()) {
              $.toast("请先选择国家");
              return
            }
            
            if(!$("#brand").val()) {
              $.toast("请先选择品牌");
              return
            }
            
            if(!$(".pick-up-id").data("country")) {
              $.toast("请重新选择取车地点", 1000);
              return
            }
            
          })
          
          $(document).on("click", ".type-item", function() {
            if(!$(".selected-val").val()) {
              $.toast("请先选择国家");
              return
            }
            
            if(!$("#brand").val()) {
              $.toast("请先选择品牌");
              return
            }
            if(!$("#method").val()) {
              $.toast("请先选择支付类型");
              return
            }
          })
        },
        
        initPicker: function() {
          var that = this;
          $("#brand").picker({
              toolbarTemplate: '<header class="bar bar-nav">\
              <button class="button button-link pull-right close-picker">关闭</button>\
              <h1 class="title">请选择品牌</h1>\
              </header>',
              cols: [
                {
                  textAlign: 'center',
                  displayValues: ['爱美路', '爱美路1'],
                  values: ['爱美路', '爱美路1']
                }
              ],
              onOpen: function(picker) {
                var supplierss = [];
                var codes = [];
                for(var i in that.countrySuppliers) {
                  var code = that.countrySuppliers[i]
                  var supplierName = that.suppliers[code].chinese_name;
                  var supplierId = that.suppliers[code].id;
                  supplierss.push(supplierName)
                  codes.push(supplierId)
                }
                console.log(supplierss);
                picker.cols[0].replaceValues(codes, supplierss)
                picker.updateValue();
                console.log(picker)
              },onClose: function() {
                that.initSets();
              },formatValue: function (picker, value, displayValue){
                $("#brand").next().val(value);
                return displayValue;
              }
          });
                
          $("#age").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">标题</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['19', '20', '21', '22', '23','24', '25', '26', '27', '28', '29', '30', '30+']
              }
            ]
          });
          $("#method").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">标题</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                displayValues: ['预付', '到付'],
                values: ['PREPAY', 'ARRIVEPAY']
              }
            ],onOpen: function(picker) {
              picker.cols[0].replaceValues(that.payCode, that.payName)
              picker.updateValue();
            },onClose: function() {
                that.initSets();
            },formatValue: function (picker, value, displayValue){
              $("#method").next().val(value);
              return displayValue;
            }
          });
          $("#package-type").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">标题</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['套餐类型', '套餐类型套餐类型套餐类型']
              }
            ],onOpen: function(picker) {
              var setsName = [];
              var setsCode = [];
              for(var i in that.setsSelect) {
                setsName.push(that.setsSelect[i].chinese_name)
                setsCode.push(that.setsSelect[i].id)
                picker.cols[0].replaceValues(setsCode, setsName)
                picker.updateValue();
              }
            },onClose: function(picker) {
            	var startTime = Date.parse(new Date($("[name='pickupDate']").val().replace(/-/g, '/'))); // 开始时间
                var endTime = Date.parse(new Date($("[name='returnDate']").val().replace(/-/g, '/'))); // 结束时间
                if(picker.value == 3 && (Math.floor((endTime - startTime) / 1000 / 60 / 60 / 24) < 4)) {
                  $.toast("取还车时间间隔不足四天")
                  $("#package-type").next().val("");
                  $(this.input).val("");
                  return;
                }
            },formatValue: function (picker, value, displayValue){
              var startTime = Date.parse(new Date($("[name='pickupDate']").val())); // 开始时间
              var endTime = Date.parse(new Date($("[name='returnDate']").val())); // 结束时间
              $("#package-type").next().val(value);
              return displayValue;
            }
          });
        },
        
        initSets: function(countryId) {
          try {
            var that = this;
            console.log(that.sets)
            var sets = null;
            var countryCode = $("input[name='countryCode']").val();
            var countryCodes = countryCode.split(",");
            
            var supplierId = $("input[name='supplierId']").val();
            var brandName = $("#brand").val() == "爱路美" ? "alamo" : $("#brand").val();
            var payType = $("input[name='type']").val();
            
            var pickuplocationVal = $(".pick-up-id").val();
            
            var setsSelect = {};
            var payTypeSets = {};
            var categoriesId = [];
            var sets = {};
            if(countryCodes.length == 1) {
              sets = that.sets[countryCodes][supplierId]
            } else {
              if(pickuplocationVal && $(".pick-up-id").data("country")) {
                console.log($(".pick-up-id").data("country"))
                sets = that.sets[$(".pick-up-id").data("country")][supplierId]
              } else if(pickuplocationVal && !$(".pick-up-id").data("country")) {
                $("#method").prop("disabled", true);
                $("#package-type").prop("disabled", true);
              }
            }
            
          
            var payCode = [];
            var payName = [];
            var categotiesArray = [];
            for(var i in sets) {
              var payTypeCode = sets[i].pay_type
              var categoties = sets[i].categoty
              if(categoties && ($.inArray(payTypeCode,payCode)==-1)) {
                categotiesArray.push(categoties)
              }
            
              if(payTypeCode && payTypeCode == "ARRIVEPAY" && ($.inArray(payTypeCode,payCode)==-1)) {
                payCode.push(payTypeCode)
                payName.push("到付")
              } else if(payTypeCode && (payTypeCode.indexOf("_PREPAY") > 0) && ($.inArray("PREPAY",payCode)==-1)) {
                payCode.push("PREPAY")
                payName.push("预付")
              }
            }
              
            if(categotiesArray.length == 1 && payName.length == 1) {
              //只有一种支付方式并且只有一种套餐
              var categoriesId = sets[0].categoty
              var setCategories = that.setCategories[categoriesId]
              $("#method").val(payName[0]);
              $("input[name='type']").val(payCode[0]);
              $("#package-type").val(setCategories.chinese_name)
              $("input[name='setCategoryId']").val(setCategories.id)
              
              setsSelect[categotiesArray[0]] = that.setCategories[categotiesArray[0]]
              that.payName = payName;
              that.payCode = payCode;
              that.setsSelect = setsSelect;
              console.log("init", that.payName)
            } else if(payName.length >1 && categotiesArray.length > 1) {
              for(var i in categotiesArray) {
                var id = categotiesArray[i]
                if(that.setCategories[id]) {
                  setsSelect[id] = that.setCategories[id]
                }
              }
              setsSelect[categotiesArray[0]] = that.setCategories[categotiesArray[0]]
            }
              
            
            /*if(payType == "ARRIVEPAY") {
              for(var i in sets) {
                if(sets[i].pay_type == "ARRIVEPAY")
                categoriesId.push(sets[i].categoty)
              }
            } else if (payType == "PREPAY") {
              for(var i in sets) {
                if(sets[i].pay_type == "COMMON_PERPAY" || "FLOAT_PAY")
                categoriesId.push(sets[i].categoty)
              }
            }
            
            for(var i in categoriesId) {
              var id = categoriesId[i]
              if(that.setCategories[id]) {
                setsSelect[id] = that.setCategories[id]
              }
            }*/
            
            that.payName = payName;
            that.payCode = payCode;
            that.setsSelect = setsSelect;
            console.log(setsSelect)
          } catch (e) {
          }
          
        },
        
        initSelectCity: function() {
          var that = this;
          $(document).on("click", ".city-popup .item-inner .item-title", function(e) {
            e.preventDefault();
            var currentName = $(this).data("name")
            var currentId = $(this).data("id")
            var countrycode = $(this).data("code");
            var countrycodes = countrycode.split(",");
            $(".city-name").addClass("hide");
            for(var i in countrycodes) {
              $(".city-name").each(function(e){
                if($(this).data("country") == countrycodes[i]) {
                  $(this).removeClass("hide")
                }
              })
            }

            that.countrySuppliers = $(this).data("suppliers").split(",");
            $(".selected-val").val(currentName)
            $("input[name='countryId']").val(currentId)
            $("input[name='countryCode']").val(countrycode)
            $.closeModal(".city-popup");
            $("#brand").prop("disabled", false)
            
            $("#brand").val(that.suppliers[that.countrySuppliers[0]].chinese_name)
            $("[name='supplierId']").val(that.suppliers[that.countrySuppliers[0]].id)
            $("#brand").trigger("change")
            $("#method").trigger("change")
            //that.initSets();
            $(".pickup input, .dropoff input, .type-item input, .method-item input").val("")
            
          })
          
          $(document).on("click", ".pickup, .dropoff", function(e) {
            e.preventDefault();
            if(!$("input[name='supplierId']").val()) { 
              $.toast("请先选择品牌");
            } else {
              that.currentPopup = $(e.currentTarget)
              var countryIdVal = $("input[name='countryId']").val();
              var supplierIdVal = $("input[name='supplierId']").val()
              if(countryIdVal && supplierIdVal) {
                $.popup('.search-page');
              } else {
                $.toast("请先选择国家");
              }
            }
          })
          
//          $(document).on("click", ".dropoff", function(e) {
//            e.preventDefault();
//            var countryId = $("input[name='countryId']");
//            if(countryId.val()) {
//              $.popup('.drop-off-popup');
//            } else {
//              $.toast("请先选择国家");
//            }
//          })
          
          
//          $(document).on("click", ".drop-off-popup .item-inner .item-title", function(e) {
//            e.preventDefault();
//            var country = $(this).data("country")
//            var city = $(this).data("city")
//            var supplierId = $("input[name='supplierId']").val();
//            var container = $(this).parents(".item-inner").find(".item-text");
//            $.showPreloader('正在查询该城市门店')
//            $.ajax({
//              type: "GET",
//              url: window.__CTX__.root + "/cars/locations?country="+country+"&city="+city + "&supplierId=" + supplierId,
//              dataType: "json",
//              success: function(data) {
//                $.hidePreloader();
//                if(data.code == 0) {
//                  var html = '<ul class="location-group">';
//                  var locations = data.data.locations;
//                  for(var i in locations) {
//                    html = html + '<li class="location" data-id="'+locations[i].id+'" data-code="'+locations[i].code+'" data-name="'+locations[i].name+'">'+locations[i].name+'</li>'
//                  }
//                  html = html + '</ul>';
//                  console.log(html)
//                  console.log($(this).parents(".item-inner").find(".item-text"))
//                  container.empty().html(html).removeClass("hide");
//                } else {
//                  $.toast(data.message);
//                }
//              },
//              error: function() {
//                $.toast("查询失败");
//              }
//            })
//          })
          
//          $(document).on("click", ".drop-off-popup .location", function(e) {
//            var id = $(this).data("id")
//            var code = $(this).data("code")
//            var name = $(this).data("name")
//            $(".drop-off-val").val(name)
//            $(".drop-off-id").val(id)
//            $.closeModal(".drop-off-popup");
//          })
//          
//          $(document).on("click", ".pick-up-popup .location", function(e) {
//            var id = $(this).data("id")
//            var code = $(this).data("code")
//            var name = $(this).data("name")
//            $(".pick-up-val").val(name)
//            $(".pick-up-id").val(id)
//            $(".drop-off-val").val(name)
//            $(".drop-off-id").val(id)
//            $.closeModal(".pick-up-popup");
//          })
          
//          $(document).on("click", ".pick-up-popup .item-inner .item-title", function(e) {
//            e.preventDefault();
//            var country = $(this).data("country")
//            var city = $(this).data("city")
//            var supplierId = $("input[name='supplierId']").val();
//            var container = $(this).parents(".item-inner").find(".item-text");
//            $.showPreloader('正在查询该城市门店')
//            $.ajax({
//              type: "GET",
//              url: window.__CTX__.root + "/cars/locations?country="+country+"&city="+city + "&supplierId=" + supplierId,
//              dataType: "json",
//              success: function(data) {
//                $.hidePreloader();
//                if(data.code == 0) {
//                  var html = '<ul class="location-group">';
//                  var locations = data.data.locations;
//                  for(var i in locations) {
//                    html = html + '<li class="location" data-id="'+locations[i].id+'" data-code="'+locations[i].code+'" data-name="'+locations[i].name+'">'+locations[i].name+'</li>'
//                  }
//                  html = html + '</ul>';
//                  console.log(html)
//                  console.log($(this).parents(".item-inner").find(".item-text"))
//                  container.empty().html(html).removeClass("hide");
//                } else {
//                  $.toast(data.message);
//                }
//              },
//              error: function() {
//                $.toast("查询失败");
//              }
//            })
//          })
        },
        
        initDatetimePicker: function() {
          var that = this;
          var calendar = new datePicker();
          var calendar1 = new datePicker();
          
//          if($("[name='pickupDate']").val() && $("[name='returnDate']").val()) {
//            calendar.init({
//              'trigger': '.pick-up-datetime', /*按钮选择器，用于触发弹出插件*/
//              'type': 'datetime',/*模式：date日期；datetime日期时间；time时间；ym年月；*/
//              'minDate': $("[name='pickupDate']").val() ,/*最小日期*/
//              'onSubmit':function(){/*确认时触发事件*/
//                var year = calendar.value.split(" ")[0];
//                var time = calendar.value.split(" ")[1];
//                var date = year.split("-")[0] + "年" + year.split("-")[1] + "月" + year.split("-")[2]+"日";
//                $(this.trigger).parents(".col-50").find(".name").html(date);
//                $(this.trigger).parent(".item-input").find('.time-box').html(time)
//                $(this.trigger).next().val(calendar.value);
//                that.dropVal = that.formatDate(calendar.value)
//              },
//            });
//            calendar1.init({
//                'trigger': '.drop-off-datetime', /*按钮选择器，用于触发弹出插件*/
//                'type': 'datetime',/*模式：date日期；datetime日期时间；time时间；ym年月；*/
//                'minDate': $("[name='returnDate']").val() ,/*最小日期*/
//                'onSubmit':function(){/*确认时触发事件*/
//                  var year = calendar1.value.split(" ")[0];
//                  var time = calendar1.value.split(" ")[1]
//                  var date = year.split("-")[0] + "年" + year.split("-")[1] + "月" + year.split("-")[2]+"日";
//                  $(this.trigger).parents(".col-50").find(".name").html(date);
//                  $(this.trigger).parent(".item-input").find('.time-box').html(time)
//                  $(this.trigger).next().val(calendar1.value)
//                },
//              });
//          } else {
            if(!$("[name='pickupDate']").val() && !$("[name='returnDate']").val()) {
              $(".pick-up-layout").find(".name").html(new Date().getFullYear()+'年'+((new Date().getMonth()+1) < 10 ? '0'+ (new Date().getMonth()+1) : (new Date().getMonth()+1))+'月'+new Date().getDate())+ '日'
              $(".drop-off-layout").find(".name").html(new Date().getFullYear()+'年'+((new Date().getMonth()+1) < 10 ? '0'+ (new Date().getMonth()+1) : (new Date().getMonth()+1))+'月'+new Date().getDate())+ '日'            
            }
            
            calendar.init({
              'trigger': '.pick-up-datetime', /*按钮选择器，用于触发弹出插件*/
              'type': 'datetime',/*模式：date日期；datetime日期时间；time时间；ym年月；*/
              'minDate':new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+(new Date().getDate()-1),/*最小日期*/
              'onSubmit':function(){/*确认时触发事件*/
                var year = calendar.value.split(" ")[0];
                var time = calendar.value.split(" ")[1];
                var date = year.split("-")[0] + "年" + year.split("-")[1] + "月" + year.split("-")[2]+"日";
                $(this.trigger).parents(".col-50").find(".name").html(date);
                $(this.trigger).parent(".item-input").find('.time-box').html(time)
                $(this.trigger).next().val(calendar.value);
                that.dropVal = that.formatDate(calendar.value)
              },
            });
            
            calendar1.init({
                'trigger': '.drop-off-datetime', /*按钮选择器，用于触发弹出插件*/
                'type': 'datetime',/*模式：date日期；datetime日期时间；time时间；ym年月；*/
                'maxDate':'2100-12-31',/*最大日期*/
                'minDate':new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+(new Date().getDate() - 1),/*最小日期*/
                'onSubmit':function(){/*确认时触发事件*/
                  var year = calendar1.value.split(" ")[0];
                  var time = calendar1.value.split(" ")[1]
                  var date = year.split("-")[0] + "年" + year.split("-")[1] + "月" + year.split("-")[2]+"日";
                  $(this.trigger).parents(".col-50").find(".name").html(date);
                  $(this.trigger).parent(".item-input").find('.time-box').html(time)
                  $(this.trigger).next().val(calendar1.value)
                },
              });
//          }
          
//          $(document).on("change", ".pick-up-datetime", function() {
//            var calendar2 = new datePicker();
//              calendar2.init({
//                'trigger': '.drop-off-datetime', /*按钮选择器，用于触发弹出插件*/
//                'type': 'datetime',/*模式：date日期；datetime日期时间；time时间；ym年月；*/
//                'minDate':that.dropVal,/*最小日期*/
//                'onSubmit':function(){/*确认时触发事件*/
//                  var year = calendar2.value.split(" ")[0];
//                  var time = calendar2.value.split(" ")[1]
//                  var date = year.split("-")[0] + "年" + year.split("-")[1] + "月" + year.split("-")[2];
//                  $(this.trigger).parents(".col-50").find(".name").html(date);
//                  $(this.trigger).parent(".item-input").find('.time-box').html(time)
//                  $(this.trigger).next().val(calendar.value)
//                },
//              });
//          })
          
//          $(".pick-up-datetime").datetimePicker({
//           minuteStep :'30',
//           onChange:function(p, values, displayValues) {
//              var date = values[0]+"年"+values[1]+"年"+values[2]+"日"
//                var time = values[3]+":"+values[4]
//                $(this.input).parents(".col-50").find(".name").html(date)
//                $(this.input).parent(".item-input").find('.time-box').html(time)
//              $(this.input).next().val(values[0]+"-"+values[1]+"-"+values[2]+" " + values[3]+":"+values[4])
//            }
//          });
        },
        
        formatDate: function(str) {
          var d=new Date(str);
          
          d.setDate(d.getDate() + 1);
          var dropMonth = d.getMonth()+1;
          var dropday   = d.getDate();
          if(dropMonth < 10) {
            dropMonth = "0"+ dropMonth;
          }
          if(dropday < 10){
            dropday = "0"+dropday;
          }
          
          var dropVal = d.getFullYear()+"-"+dropMonth+"-"+dropday;
          return dropVal
        },
        
        bindSubmit: function(isLogin) {
          var that = this;
          $(".submit-button").on("click", function(e){
            e.preventDefault();
            
            var form = $("form");
            
            var supplierId = $("input[name='supplierId']").val();
            var countryId =  $("[name='countryId']").val();
            var pickupLocation =  $("[name='pickupLocation']").val();
            var returnLocation =  $("[name='returnLocation']").val();
            var pickupDate =  $("[name='pickupDate']").val();
            var returnDate =  $("[name='returnDate']").val();
            var driveAge =  $("[name='driveAge']").val();
            var type =  $("[name='type']").val();
            var setCategoryId =  $("[name='setCategoryId']").val();
            
            if(!supplierId || !countryId || !type || !pickupLocation || !returnLocation || !pickupDate || !returnDate || !driverAge || !setCategoryId) {
              $.toast("请填写完整查询条件")
              return
            }
            
            var startTime = Date.parse(new Date(pickupDate.replace(/-/g, '/'))); // 开始时间
            var endTime = Date.parse(new Date(returnDate.replace(/-/g, '/'))); // 结束时间
            
            if(setCategoryId == 3 && (Math.floor((endTime - startTime) / 1000 / 60 / 60 / 24) < 4)) {
              $.toast("取还车时间间隔不足四天");
              $("[name='setCategoryId']").val("");
              return
            }
            
            if(startTime < Date.parse(new Date().getTime() - 1000*60*60*24)) {
              $.toast("请重新选择取还车时间");
              return
            }
            
            var obj = [{
              'name': "supplierName" ,
              "value": $("#brand").val()
            },
            {
              'name': "pickupLocationName" ,
              "value": $(".pick-up-val").val()
            },
            {
              'name': "returnLocationName" ,
              "value": $(".drop-off-val").val()
            },
            {
              'name': "typeName" ,
              "value": $("#method").val()
            },
            {
              'name': "setCategoryName" ,
              "value": $("#package-type").val()
            },
            {
              'name': 'pickupLocationCountry',
              'value': $(".pick-up-id").data("country")
            }
            ]
            
            console.log(obj)
            var formObj = (form.serializeArray()).concat(obj);
            
            $.showPreloader("正在查询可用车辆");
            that.setLocalStorage(formObj)
            
            form.submit();
            
          })
        },
        initHotCity: function() {
          var that = this;
          $(document).on("open", ".search-page", function() {
            $('.hot-city-wrap .city-box').empty();
            $('.hot-city-wrap .cities-letter').empty();
          })
          
          $(document).on("opened", ".city-popup", function(e) {
            that.bindBsrollCity($(e.currentTarget));
          })
          
          $(document).on("opened", ".search-page", function(e) {
            var inputVal = $(this).val();
            var country = $("[name='countryCode']").val();
            var brandName = $("#brand").val() == "爱路美" ? "alamo" : $("#brand").val();
            
            
            var pickCityVal = that.currentPopup.hasClass('dropoff') ? ($(".dropoff .picklocation-val").val()) : ($(".pickup .picklocation-val").val());
            
            var hotCityHtml = '<% for(var i in hotLocation){ %>'
                            + '<div class="city-list">'
                            + '<div class="city-index"><%= i %></div>'
                            + '<div class="cities-name row">'
                            + '<% hotLocation[i].forEach(function(value, key){ %>'
                            + '<% if( value.name == pickCityVal) { %>'
                            + '<div class="item col-50 active" data-name="<%= value.name %>" data-country="<%= value.country %>" data-id="<%= value.id %>"><%= value.chineseCityName %><span><%= value.englishCityName%></span></div>'
                            + '<% } else { %>'
                            + '<div class="item col-50" data-name="<%= value.name %>" data-country="<%= value.country %>" data-id="<%= value.id %>"><%= value.chineseCityName %><span><%= value.englishCityName%></span></div>'
                            + '<% } %>'
                            + '<% }) %>'
                            + '</div>'
                            + '</div>'
                            + '<% } %>';
            
            var hotLetterHtml = '<ul>'
                              + '<% for(var i in hotLocation){  %>'
                              + '<li><a href="javascript:void(0);" class="external"><%= i %></a></li>'
                              + '<% } %>'
                              + '<li><a href="javascript:void(0);" class="external"></a></li>'
                              + '</ul>';
            
            $.showPreloader('正在查询该城市热门门店')
            
            $.ajax({
              type: "GET",
              url: window.__CTX__.root + "/cars/search-hot-location",
              dataType: "json",
              data: {
                country: country,
                brand: brandName,
              },
              success: function(data) {
                $.hidePreloader();
                var hotLocations = data.data.locations;
                if(data.code == 0) {
                  if(hotLocations && JSON.stringify(hotLocations) != "{}") {
                    var result = ejs.render(hotCityHtml, {
                        hotLocation : hotLocations,
                        pickCityVal : pickCityVal
                      })
                      
                    var letterResult = ejs.render(hotLetterHtml, {
                         hotLocation : hotLocations,
                      })
                    $('.hot-city-wrap .city-box').empty().html(result);
                    $('.hot-city-wrap .cities-letter').empty().html(letterResult);
                    
                    that.bindBsrollCity($(e.currentTarget));
                  } else {
                    $('.hot-city-wrap .city-box').empty().html('<p class="text-center" style="font-size: .8rem; color: #999;">暂无数据</p>')
                    $('.hot-city-wrap .cities-letter').empty().html("");
                  }
                } else {
                    $.toast(data.message);
                }
              },
              error: function() {
                $.toast("查询失败");
                that.clearContent();
              }
            })
            
        })
      },
      
      bindCitySearch: function() {
        var that = this;
        var cityHtml = '<div class="list-block no-margin">'
		               + '<ul>'
		               + '<% locations.forEach(function(item, index){ %>'
		               + '<li class="item-content" data-name="<%= item.name %>" data-country="<%= item.country %>" data-id="<%= item.id %>">'
		               + '<div class="item-inner">'
		               + '<div class="item-title">'
		               + '<div class="name"><%= item.name %></div>'
		               + '<div class="description">'
		               + '<p style="margin: 0;"><%= item.address1 %>&nbsp;&nbsp;<%= item.address2 %></p>'
		               + '<p style="margin: 0;">TEL:<%= item.phone %>;&nbsp;&nbsp;<%= item.country %>&nbsp;<%= item.cityName %></p></div>'
		               + '</div>'
		               + '<div class="item-after">'
		               + '<% if (item.isAirport) { %>'
		               + '<i class="iconfont iconfont-airplane"></i>'
		               + '<% } %>'
		               + '</div>'
		               + '</div>'
		               + '</li>'
		               + '<% }) %>'
		               + '</ul>'
		               + '</div>';
        
        $('#search').on('focus', function(e) {
          $(".hot-city-wrap").hide();
          $(".search-list-wrap").show();
        })
        
        $('#search').on('input', function(e) {
          var inputVal = $(this).val();
          var country = $("[name='countryCode']").val();
          var brandName = $("#brand").val() == "爱路美" ? "alamo" : $("#brand").val();
          if(inputVal && inputVal.length >=2) {
            //输入框内容不为空请求数据
            $.showPreloader('正在查询该城市门店')
            $.ajax({
              type: "GET",
              url: window.__CTX__.root + "/cars/search-location",
              dataType: "json",
              data: {
                country: country,
                brand: brandName,
                code: inputVal,
              },
              success: function(data) {
                $.hidePreloader();
                var locations = data.data.locations;
                if(data.code == 0) {
                  
                  if(locations) {
                    var result = ejs.render(cityHtml, {
                        locations : locations
                    })
                    $('.search-list-wrap').empty().html(result);
                  } else {
                    $('.search-list-wrap').empty().html('<p class="text-center" style="font-size: .8rem; color: #999;">暂无数据</p>')
                  }
                } else {
                  $.toast(data.message);
                }
              },
              error: function() {
                $.toast("查询失败");
                that.clearContent();
              }
            })
          }
        })
        
        $(document).on("click", ".search-list-wrap .item-content, .hot-city-wrap .cities-name .item", function(e) {
          
          that.pickName = $(e.currentTarget).data("name")
          that.pickId = $(e.currentTarget).data("id")
          that.pickCountry = $(e.currentTarget).data("country")
          that.currentPopup.find(".picklocation-val").val(that.pickName)
          that.currentPopup.find(".picklocation-id").val(that.pickId)
          that.currentPopup.find(".picklocation-id").data("country",that.pickCountry)
          $.closeModal(".search-page");
          that.clearContent();
        })
        
        $(document).on("click", ".searchbar-cancel", function() {
          that.clearContent();
        })
        
        $(document).on("click", ".fita-header .back", function() {
          $.closeModal(".search-page")
          that.clearContent();
        })
        
        $(document).on("close", ".search-page", function(e) {
          var dropoffVal = $(".dropoff").find(".picklocation-val").val();
          $("#method").prop("disabled", false)
          if(!that.currentPopup.hasClass("dropoff") && !dropoffVal) {
            $(".dropoff").find(".picklocation-val").val($(".pickup .picklocation-val").val())
            $(".dropoff").find(".picklocation-id").val($(".pickup .picklocation-id").val())
          }
          
          if(that.currentPopup.hasClass("pickup")) {
            $("#method").val("");
            $("input[name='type']").val("");
            $("#package-type").val("");
            $("input[name='setCategoryId']").val("");
          }
          
          that.initSets();
        })
      },
      
      bindBsrollCity: function($this) {
        var listWrapper =$this[0].querySelector(".list-wrapper");
        var listWrapperItems = listWrapper.querySelectorAll(".city-box .city-list")
        var indexNavList = $this[0].querySelector(".cities-letter");
        var indexNavListUl = indexNavList.querySelector("ul");
        var indexNavListItems = indexNavListUl.children;
        var indexNavListUlTop = indexNavListUl.offsetTop;
        var indexNavListItemHeight = indexNavListUl.children[0].offsetHeight;
        
        var bScroll = new BScroll(listWrapper, {
          probeType: 3,
          bounce: false,
          click: true,
          taps: true
        });
          
          var len = listWrapperItems.length;
          bScroll.on("scroll", function(e){
            var y = -e.y;
            if (y < listWrapperItems[0].offsetTop) {
              setNav (0);
              return;
            }
            for (var i=0; i<len-1; i++) {
              if (y >= listWrapperItems[i].offsetTop && y < listWrapperItems[i+1].offsetTop) {
                setNav (i);
                return;
              }
            }
            setNav (len-1);
          });
  
         indexNavListUl.addEventListener("touchstart", function(e){
           var touch = e.changedTouches[0];
           setIndex (touch.clientY)
         });
         
         indexNavListUl.addEventListener("touchmove", function(e){
           var touch = e.changedTouches[0];
           setIndex (touch.clientY)
         });
         
         //设置
         function setIndex (y) {
           var index = getIndex (y);
           if (index >=0 && index < len) {
             bScroll.scrollToElement(listWrapperItems[index],100);
             setNav (index);
             // tabMark (index);
           }
         }
         
         //获取索引
         function getIndex (y) {
           return parseInt((y - indexNavListUlTop) / indexNavListItemHeight);
         }
         
         function setNav (index) {
           for (var i=0; i<indexNavListItems.length; i++) {
             indexNavListItems[i].classList.remove("active");
           }
           indexNavListItems[index].classList.add("active");
         }
      },
      
      clearContent: function() {
        //清除搜索结果
        $("#search").val("");
        $(".hot-city-wrap").show();
        $(".search-list-wrap").hide();
      },
      
      setLocalStorage: function(obj) {
        if(!window.localStorage){
          alert("浏览器支持localstorage");
        }else{
          var storage=window.localStorage;
            storage.removeItem("localData");
            storage.setItem("localData",JSON.stringify(obj));
            console.log('local',storage.data)
        }
      }
    }
  })